package com.promise.jokerdream.work.faction

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.PhoneGameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryFactionMinePCResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import kotlinx.coroutines.delay

// 矿洞工作
class FactionMineWork(uin: String): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val phoneGameApi = PhoneGameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "矿洞"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 先查询矿洞信息
            val queryResult = gameApi.queryFactionMine()
            queryResult.foldWithApiException(
                onSuccess = { mineInfo ->
                    // 处理查询成功
                    handleMineQuery(mineInfo)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
            
            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e)
        }
    }
    
    /**
     * 处理矿洞查询结果
     */
    private suspend fun handleMineQuery(mineInfo: QueryFactionMinePCResponse) {
        // 2. 如果有奖励消息，先领奖
        if (mineInfo.rewardMessage.isNotEmpty()) {
            val claimResult = gameApi.claimFactionMineReward()
            claimResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        }
        
        // 3. 根据剩余次数决定是否挑战
        val remainingTimes = 3 - mineInfo.fightTimes
        if (remainingTimes <= 0) {
            return
        }

        if (mineInfo.rewardMessage.isNotEmpty()) {
            // 傻逼乐斗不给卡矿洞的后果
            delay(3000) // 等待3秒
        }
        
        // 4. 开始挑战循环
        var currentRemainingTimes = remainingTimes
        while (currentRemainingTimes > 0) {
            // 挑战矿洞
            val fightResult = phoneGameApi.fightFactionMine()
            fightResult.foldWithApiException(
                onSuccess = { fightData ->
                    historyManager.addHistory(name, fightData.actionResult)
                    
                    // 检查是否通关
                    if (fightData.isPass) {
                        // 通关后直接领奖
                        val finalClaimResult = gameApi.claimFactionMineReward()
                        finalClaimResult.foldWithApiException(
                            onSuccess = { response ->
                                historyManager.addHistory(name, response.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                        return
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return
                }
            )
            
            currentRemainingTimes--
            
            // 如果还有剩余次数，等待一下再继续
            if (currentRemainingTimes > 0) {
                delay(3000) // 等待3秒
            }
        }
    }
}